<template>
  <div>
    <v-btn @click="getContentFn">content</v-btn>
    <div class="editor" ref="editor" contenteditable="true" @keyup="changeFn" @keydown="keydownFn">
      <div>select * from table_name</div>
    </div>
    <div v-html="html"></div>
  </div>
</template>

<script>
// import 'highlight.js/styles/default.css'

import 'github-markdown-css/github-markdown.css';
const marked = require('marked')
// const highlight = require('highlight.js')
marked.setOptions({
  renderer: new marked.Renderer(),
  // highlight: function (code, lang) {
  //   const language = highlight.getLanguage(lang) ? lang : 'plaintext'
  //   return highlight.highlight(code, { language }).value
  // },
  pedantic: false,
  gfm: true,
  breaks: false,
  sanitize: false,
  smartLists: true,
  smartypants: false,
  xhtml: false
})
export default {
  name: 'MarkdownEditor',
  data() {
    return {
      range: '0',
      html: ''
    }
  },
  methods: {
    changeFn() {
      this.getContentFn()
    },
    insert(node) {
      this.$refs.editor.focus()
      setTimeout(() => {
        let range = document.getSelection().getRangeAt(0)
        range.setStart(range.endContainer, range.endOffset)
        range.insertNode(node)
        range.detach()
        range = document.getSelection().getRangeAt(0)
        range.setStart(range.endContainer, range.endOffset)
        range.detach()
      })
    },
    keydownFn(e) {
      if (e.key === 'Tab') {
        e.preventDefault()
        let s = document.createElement('span')
        s.innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;'
        this.insert(s)
      }
    },
    getContentFn() {
      const text = this.$refs.editor.innerText
      this.html = marked(text)
    }
  }
}
</script>

<style scoped lang="scss">
.editor {
  outline: none;
  padding: 5px;
  margin: 5px;
  border: 1px solid #eee;
}
</style>
